package top.yaofengqiao.springcloudsimple.auth.biz.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.security.manager.OauthAuthenticationManager;

import javax.annotation.Resource;

/**
 * @author yfq
 * @date 2024/5/31 15:44
 * @description Spring Security配置
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private AuthenticationProvider adminAuthenticationProvider;
    @Resource
    private AuthenticationProvider memberAuthenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 1. 基本配置
        http
                // 允许跨域
                .cors()
                .and()
                // 关闭csrf
                .csrf().disable()
                // 不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // 2. 权限配置
        http.authorizeRequests()
                // 静态资源，可匿名访问(swagger文档)
                .antMatchers(HttpMethod.GET, "/*.html", "/**/*.html", "/**/*.css", "/**/*.js").permitAll()
                // 登录接口放行
                .antMatchers("/rsa/publicKey", "/oauth/usernameLogin", "/oauth/refreshToken", "/oauth/oauth2Login", "/oauth/oauth2LoginUrl/*").permitAll()
                // 其他接口需要鉴权
                .anyRequest().authenticated();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(memberAuthenticationProvider);
        auth.authenticationProvider(adminAuthenticationProvider);
    }

    /**
     * 认证管理器
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() {
        return oauthAuthenticationManager();
    }

    /**
     * 自定义认证管理器
     */
    @Bean
    public AuthenticationManager oauthAuthenticationManager() {
        return new OauthAuthenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
